package com.nova.android.tvlauncher.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.nova.android.tvlauncher.bean.HomeHeaderDto
import com.nova.android.tvlauncher.databinding.ItemMainTabBinding
import com.nova.android.tvlauncher.databinding.ViewMainTopBinding
import com_github_lib_base.view.rv.addModels
import com_github_lib_base.view.rv.multiTypeAdapter

class MainTopView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    // 初始化视图
    private var binding: ViewMainTopBinding =
        ViewMainTopBinding.inflate(LayoutInflater.from(context), this, true)

    // 定义回调接口
    var onTabFocusChanged: ((HomeHeaderDto, Int, Boolean) -> Unit)? = null

    init {

        setupListeners()
    }

    fun setTabData(newList:MutableList<HomeHeaderDto>){
        binding.rvTab.addModels(newList)
        binding.rvTab.apply {
            post {
                requestFocus()
            }
        }
    }


    private fun setupListeners() {
        binding.rvTab.multiTypeAdapter<HomeHeaderDto> {
            registerType {
                match<ItemMainTabBinding>(
                    predicate = { true },
                ){item,position->
                    tvTabName.text = item.name
                    tvTabName.setOnFocusChangeListener { v, hasFocus ->
                        //通过DSL把焦点状态和position回调出来
                        if(hasFocus)onTabFocusChanged?.invoke(item, position, hasFocus)
                    }
                }
            }
        }


    }


}
